﻿using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;

namespace PraiseSystem.Models
{
    /// <summary>
    /// Create PraiseDBContext derived from DbContext.
    /// </summary>
    class PraiseDBContext:DbContext
    {
        public virtual DbSet<Praise> Praises { get; set; }
        public virtual DbSet<User> Users { get; set; }
        public virtual DbSet<Receiver> Receivers { get; set; }

        /// <summary>
        /// Create models through dynamic method, this will call automaticly for code first(not database first).
        /// </summary>
        /// <param name="modelBuilder">The core of code first</param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Get mapping types derived from EntityTypeConfiguration
            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(type => !string.IsNullOrEmpty(type.Namespace))
                .Where(type => type.BaseType != null 
                && type.BaseType.IsGenericType 
                && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
           
            //Register types.
            foreach (var type in typesToRegister)
            {
                dynamic configInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configInstance);
            }

            base.OnModelCreating(modelBuilder);
        }
    }

  

 

 
}
